package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.EsConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrVo;
import com.atguigu.gulimall.search.vo.EsSearchResult;
import com.atguigu.gulimall.search.vo.SearchParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    RestHighLevelClient restHighLevelClient;
    @Resource
    ProductFeignService productFeignService;

    @Override
    public EsSearchResult search(SearchParam param) {
        //动态构建出查询需要的DSL语句
        EsSearchResult searchResult = null;

        //1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            //2、执行检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, EsConfig.COMMON_OPTIONS);

            //3、分析响应数据封装成需要的格式
            searchResult = buildSearchResult(response, param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    /**
     * 构建结果数据
     * @param response
     *
     * @return
     */
    private EsSearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        EsSearchResult esSearchResult = new EsSearchResult();

        SearchHits hits = response.getHits();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            //1、返回所有查询到的商品
            List<SkuEsModel> esModels = new ArrayList<>();
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                esModels.add(skuEsModel);
            }
            esSearchResult.setProducts(esModels);

            //========= 从聚合结果获取数据 =========

            //2、当前所有商品涉及到的所有属性信息
            List<EsSearchResult.AttrVO> attrVOs = new ArrayList<>();
            ParsedNested attr_agg = response.getAggregations().get("attr_agg");
            ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
            for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
                EsSearchResult.AttrVO attrVO = new EsSearchResult.AttrVO();
                //1、得到属性的ID
                long attrId = bucket.getKeyAsNumber().longValue();
                attrVO.setAttrId(attrId);
                //2、得到属性的名字
                String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
                attrVO.setAttrName(attrName);
                //3、得到属性的所有值
                List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(vo -> vo.getKeyAsString()).collect(Collectors.toList());
                attrVO.setAttrValue(attrValues);
                attrVOs.add(attrVO);
            }
            esSearchResult.setAttrs(attrVOs);

            //3、当前所有商品涉及到的所有品牌信息
            List<EsSearchResult.BrandVO> brandVOs = new ArrayList<>();
            ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
            for (Terms.Bucket bucket : brand_agg.getBuckets()) {
                EsSearchResult.BrandVO brandVO = new EsSearchResult.BrandVO();
                //1、得到品牌ID
                long keyAsString = bucket.getKeyAsNumber().longValue();
                brandVO.setBrandId(keyAsString);
                //2、得到品牌名称
                String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
                brandVO.setBrandName(brandName);
                //3、得到品牌图片
                String branImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
                brandVO.setBrandImg(branImg);
                brandVOs.add(brandVO);
            }
            esSearchResult.setBrands(brandVOs);

            //4、当前商品设计到的所有分类信息
            ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
            List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
            ArrayList<EsSearchResult.CatalogVO> catalogVOs = new ArrayList<>();
            for (Terms.Bucket bucket : buckets) {
                EsSearchResult.CatalogVO catalogVO = new EsSearchResult.CatalogVO();
                //得到分类ID
                String keyAsString = bucket.getKeyAsString();
                catalogVO.setCatalogId(Long.valueOf(keyAsString));
                //得到分类名
                ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
                catalogVO.setCatalogName(catalog_name);
                catalogVOs.add(catalogVO);
            }
            esSearchResult.setCatalogs(catalogVOs);
        }
        //4、分页信息-页码
        Integer pageNum = param.getPageNum();
        esSearchResult.setPageNum(pageNum);
        //5、分页信息-总记录数
        long total = hits.getTotalHits().value;
        esSearchResult.setTotal(total);
        //6、分页信息-总页码(计算公式：总记录数 / 每页数据量 = 总页码 ，余数不等于0则加1)
        int totalPages = total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : (int) total / EsConstant.PRODUCT_PAGESIZE + 1;
        esSearchResult.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 0; i < totalPages; i++) {
            pageNavs.add(i + 1);
        }
        esSearchResult.setPageNavs(pageNavs);
        //7、构建面包屑导航功能
        if (param.getAttrs() != null && !param.getAttrs().isEmpty()) {
            List<EsSearchResult.NavVO> collect = param.getAttrs().stream().map(attr -> {
                //分析每个attrs传过来的查询参数值
                EsSearchResult.NavVO navVO = new EsSearchResult.NavVO();
                //attrs格式：规格id_规格值1:规格值2
                String[] s = attr.split("_");
                navVO.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                esSearchResult.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrVo data = r.getData("attr", new TypeReference<AttrVo>() {
                    });
                    navVO.setNavName(data.getAttrName());
                } else {
                    navVO.setNavName(s[0]);
                }
                //取消面包屑以后，要跳转到哪个地方，将请求地址的url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String replace = replaceQueryString(param.get_queryString(), "attrs", attr);
                navVO.setLink("http://search.gulimall.com/list.html?" + replace);


                return navVO;
            }).collect(Collectors.toList());
            esSearchResult.setNavs(collect);
        }

        //品牌
        if (param.getBrandId() != null && !param.getBrandId().isEmpty()) {
            List<EsSearchResult.NavVO> navs = esSearchResult.getNavs();
            EsSearchResult.NavVO navVO = new EsSearchResult.NavVO();
            navVO.setNavName("品牌");
            //远程查询所有品牌
            R r = productFeignService.brandsInfo(param.getBrandId());
            if (r.getCode() == 0) {
                List<EsSearchResult.BrandVO> brands = r.getData("brand", new TypeReference<List<EsSearchResult.BrandVO>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String replace = null;
                for (EsSearchResult.BrandVO brand : brands) {
                    buffer.append(brand.getBrandName() + ";");
                    replace = replaceQueryString(param.get_queryString(), "brandId", brand.getBrandId() + "");
                }
                navVO.setNavValue(buffer.toString());
                navVO.setLink("http://search.gulimall.com/list.html?" + replace);
            }
            navs.add(navVO);
        }
        //TODO 分类：不需要导航取消


        return esSearchResult;
    }

    private String replaceQueryString(String queryString, String key, String value) {
        try {
            String encode = URLEncoder.encode(value, "UTF-8");
            //将转码后变成"+"的空格转为浏览器转义格式
            encode = encode.replace("+", "%20");
            return queryString.replace("&" + key + "=" + encode, "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构建检索请求
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        //构建DSL语句
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        /*
        模糊匹配，过滤（属性，分类，品牌，价格区间，库存）
         */
        //1、构建bool - query
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // must - 模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // filter - 按照三级分类ID查询
        if (param.getCatelog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatelog3Id()));
        }
        // filter - 按照品牌ID查询
        if (param.getBrandId() != null && !param.getBrandId().isEmpty()) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brandId", param.getBrandId()));
        }
        // filter - 按照所有指定的属性进行嵌入查询
        if (param.getAttrs() != null && !param.getAttrs().isEmpty()) {
            for (String attrStr : param.getAttrs()) {
                //参数格式 attrs=属性ID_属性值1:属性值2:
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                //检索的属性ID
                String attrId = s[0];
                //冒号分隔多个属性值
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个都都要生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);//ScoreMode.None：结果不参与评分
                boolQueryBuilder.filter(nestedQuery);
            }
        }
        // filter - 按照是否有库存进行查询
        if (param.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // filter - 按照价格进行区间查询
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            //参数格式 始值_终值/0_终值/始值_无限
            String[] s = param.getSkuPrice().split("_");
            //区间值 1 至 500
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                //字符以_开头，表示 500 以下
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                //字符以_结尾，表示 500 以上
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        searchSourceBuilder.query(boolQueryBuilder);

        //排序
        if (!StringUtils.isEmpty(param.getSort())) {
            //参数格式 排序字段_排序规则  hotScore_asc/desc
            String sort = param.getSort();
            String[] s = sort.split("_");
            //忽略大小写方式判断排序规则
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s[0], sortOrder);
        }

        //分页
        searchSourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        // 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //需要高亮的字段
            highlightBuilder.field("skuTitle");
            //样式标签 头
            highlightBuilder.preTags("<b style='color:red'>");
            //样式标签 尾
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);

        }

        //聚合分析
        //品牌聚合 聚合名称 brand_agg ，聚合字段 brandId ，聚合结果取50个
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //子聚合  brand_agg聚合下，子聚合名称 brand_name_agg ，字段 brandName ，聚合结果取1个
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);
        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);
        //属性聚合(嵌入式聚合查询)
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合出所有attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析出当前attr_id对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析出当前attr_id对应的所有属性值attrValue
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(attr_agg);


        System.out.println("构建的DSL" + searchSourceBuilder.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }
}
